package com.basics.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

/**
 * 微信手机号解析工具
 * @Author WangWei
 * @Date 2021/12/28 16:11
 * @Version 2.0
 * @Description
 **/
@Slf4j
public class WechatDecryptDataUtil {
    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;

    public WechatDecryptDataUtil() {
    }

    public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
        log.info(">>> WechatDecryptDataUtil.decryptData :{},{},{}",encryptDataB64, sessionKeyB64, ivB64);
        return new String(decryptOfDiyIV(Base64.decode(encryptDataB64), Base64.decode(sessionKeyB64), Base64.decode(ivB64)));
    }

    private static void init(byte[] keyBytes) {
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte)0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }

        Security.addProvider(new BouncyCastleProvider());
        key = new SecretKeySpec(keyBytes, "AES");

        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        } catch (Exception var4) {
            var4.printStackTrace();
        }

    }

    private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
        byte[] encryptedText = null;
        init(keyBytes);

        try {
            cipher.init(2, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return encryptedText;
    }
}

